import _ from "lodash";
//树形结构封装
export default class TreeUtils{
   //将普通结构的树封装成父子结构的树
   public static getTreeData(normalData:any,fatherItem:any){
        const children:any=normalData.filter(item=>item.pId==fatherItem.id);
        if(children.length>0){
            fatherItem.children=children;
            for(let i=0;i<children.length;i++){
                TreeUtils.getTreeData(normalData,children[i]);
            }
        }
   }
   //根据搜索的字符串重新生成树
   public static getTreeDataBySearchText(normalData:any,text:any){
         const treeData:any=normalData.filter(item=>item.label.indexOf(text)>-1);
         const resultData:any=new Array<any>();
         for(let i=0;i<treeData.length;i++){
            const currentSearchItem:any=treeData[i];
              resultData.push(currentSearchItem);
              TreeUtils.collectionFatherNodes(normalData,currentSearchItem,resultData)
         }
         const uniqRes=_.uniqBy(resultData,"id");
         return uniqRes;
   }
   //递归获取所有父亲节点
    public static collectionFatherNodes(normalData:any,currentSearchItem:any,resultData:any){
         const fatherItem:any=normalData.find(item=>item.id==currentSearchItem.pId);
         if(fatherItem){
            resultData.push(fatherItem);
            TreeUtils.collectionFatherNodes(normalData,fatherItem,resultData);
         }
    }
}
